$(function(){
	styleFn();
	MenuHandleFn();
	changeStyleFn();
	tkHandleFn();
	conHandleFn();
	$("input").focus(function () {
	    $('#cnURLError').html("");
	});
});

//定义一些样式
function styleFn(){
	var $win = $(window),
		$side = $('.side'),
		$tk = $('.tk'),
		$imgTk = $('.imgTk'),
		iWinW = $win.width(),
		iWinH = $win.height();
	
	$('#cnEPEditer').empty();
	$('.conNew').css({width: iWinW - $side.outerWidth()});
	$tk.css({top:( iWinH - $tk.outerHeight())/2});
	//$imgTk.css({top:( iWinH - $imgTk.outerHeight())/2});
	$(".imgTk").css({ "top": "96px" });
	$('.conNew, .side').css({minHeight: iWinH - 100});
	$('.mask').css({height: $(document).height()});
	if(iWinW<1024){
		$('.wrap').css({width:1024});
		$('.conNew').css({width: 1024 - $side.outerWidth()});
	}

};

//样式重置，滚动及改变浏览器大小
function changeStyleFn(){
	var $win = $(window),
		$tk = $('.tk'),
		$imgTk = $('.imgTk'),
		iTop = parseInt($tk.css('top')),
		iImgTkTop = parseInt($imgTk.css('top'));
	//弹框滚动
	$win.scroll(function(){
		$tk.stop().animate({top: iTop + $win.scrollTop()},100);
		$imgTk.stop().animate({top: iImgTkTop + $win.scrollTop()},100);
	}).resize(styleFn);
};

/*
 * 隐藏显示弹框
 * btn 布尔值 true→显示 false→隐藏
 * str 字符串 隐藏显示哪个弹框 
 */
function tkShowHideFn(str,btn){
	var $tkBox = $('.mask,.' + str);
	btn ? $tkBox.hide() : $tkBox.show();
};

//菜单操作
function MenuHandleFn(){
	
	var $oneAdd = $('.sH2 .add_gray'),
		$twoAdd = $('.menu_opr .add_gray'),
		$oneDel = $('.sDl dt .del_gray'),
		$sDl = $('.sDl'),
		$twoDel = $sDl.find('.del_gray'),
		$oneEdit = $sDl.find('dt .edit_gray'),
		$twoEdit = $sDl.find('dd .edit_gray'),
		$oneUp = $sDl.find('dt .up_gray'),
		$oneDown = $sDl.find('dt .down_gray'),
		$twoUp = $sDl.find('dd .up_gray'),
		$twoDown = $sDl.find('dd .down_gray'),
		$tk = $('.addTk'),
		$delTk = $('.delTk'),
		$sDlDt = $sDl.find('dt'),
		$sDldd = $sDl.find('dd'),
		$sArea = $('#sArea');
	
	//一级菜单添加
	$oneAdd.live('click', function () {
	    var $thisParent = $(this).parent(),
			$thisDl = $(this).closest('.sDl');
	    if ($('.sDl').length >= 3) {
	        addMoreTipFn(0);
	        return;
	    }
	    $(".tkH3").html("菜单名称名字不多于4个汉字:");
	    $tk.data({ bBig: true });
	    tkShowHideFn('addTk');

	});

	//二级菜单添加
	$twoAdd.live('click', function () {
	    
	    var $thisParent = $(this).parent(),
			$thisDl = $(this).closest('.sDl'),
			iThisDDLength = $thisDl.find('dd').length;

	    $tk.data({ iNow: $(this).closest('.sDl').index() });

	    if (iThisDDLength >= 5) {
	        addMoreTipFn(1);
	        return;
	    }
	    $(".tkH3").html("菜单名称名字不多于7个汉字:");
	    tkShowHideFn('addTk');

	});

	//一级菜单删除
	$oneDel.live('click', function () {
	    
	    $delTk.attr({ bBig: true, iNow: $(this).closest('.sDl').index() });
	    tkShowHideFn('delTk');

	});

	//二级菜单删除
	$twoDel.live('click', function () {
	    var _this = $(this),
			$thisDl = $(this).closest('.sDl');
	    $delTk.attr({ iNow: _this.closest('.sDl').index(), iDDNow: _this.closest('dd').index() - 1 });
	    tkShowHideFn('delTk');
	});

	//一级菜单移入移出
	$sDlDt.live({
	    'mouseover': function () {
	        menuOnFn($(this), true);
	    },
	    'mouseout': function () {
	        outFn('.sDl dt');
	    },
	    'click': function () {
	        var itemName = $(this).closest('dt').find("strong").html();
	        $("#acTitle").html("一级菜单：" + itemName);
	        if ($(this).closest('.sDl').find('dd').length > 0) {
	            showHideFn($('#cnTipBox'), $('.cnBoxCon'));
	            $('#cnTip').text('已有子菜单，无法设置动作');
	        } else {
	            var itemid = $(this).closest('dt').attr('id');
	            var Param = $.param({
	                mid: itemid
	            });
	            $.ajax({ url: "Ajax.aspx?action=menudesc&t=" + Math.random(),
	                type: "POST",
	                data: Param,
	                dataType: "json",
	                processData: false,
	                error: function (datas) {
	                },
	                success: function (datas) {
	                    if (datas == "" || datas == undefined) {
	                        showHideFn($('#cnHandleBox'), $('.cnBoxCon'));
	                    }
	                    else {
	                        var type = datas.type;
	                        var htmldesc = "";
	                        $('#cnURLError').html("");
	                        $('#cnEPImgTextAuto').empty();
	                        $("#cnEPEditer").val("");
	                        if (type == "text") {
	                            $('#cnTextInp').val(datas.content);
	                            $("#cnHandleBox,#cnTipBox,#cnEditBox,#cnUrlBox,#cnImgTextReadBox,#cnTextReadBox").hide();
	                            $('#cnTextBox').show();
	                            $("#cnEPEditer").val(decodeURIComponent(datas.content));
	                        } else if (type == "view") {
	                            $('#cnUrlInp').val(decodeURIComponent(datas.content));
	                            $("#cnHandleBox,#cnTipBox,#cnEditBox,#cnImgTextReadBox,#cnTextReadBox,#cnTextBox").hide();
	                            $('#cnUrlBox').show();
	                        }
	                        else if (type == "mpnew") {
	                            var list = datas.list;
	                            if (list != null && list.length > 0) {
	                                $("#cnHandleBox,#cnTipBox,#cnEditBox,#cnUrlBox,#cnTextBox,#cnTextReadBox").hide();
	                                var htmldesc = '<div class="boe7e7eb cnEPITConL" style="display: inline-block;vertical-align: bottom;" itemid="' + datas.content + '">';
	                                for (var j = 0; j < list.length; j++) {
	                                    if (j == 0) {
	                                        var sp =decodeURIComponent(list[j].simple);
	                                        htmldesc += '<h4 class="cnEPITH4">' +
                                        '<a href="#" class="c666">' + decodeURIComponent(list[j].title) + '</a>' +
                                    '</h4>' +
                                    '<p class="c666 cnEPITDate">' + list[j].date + '</p>' +
                                    '<div class="cnEPITimg db">' +
                                        '<img src="../UpFiles/res/' + list[j].logo + '" alt="图片" />' +
                                     '</div>' +
                                    '<p class="c666 cnEPITDate oh">' + (sp.length > 20 ? sp.substring(0, 20) + "......" : sp) + '</p>'
	                                    }
	                                    else {
	                                        htmldesc += '<div class="clear cnEPITDescImg">' +
                                            '<img src="../UpFiles/res/' + list[j].logo + '" class="cnEPITDescImgR fr" />' +
                                            '<div class="oh cnEPITDescImgL fl">' + decodeURIComponent(list[j].title) + '</div>' +
                                        '</div>';
	                                    }
	                                }
	                                htmldesc += "</div>";

	                                $('#cnEPImgTextAuto').empty().append(htmldesc).append('<a class="cnEPITConR" style="display: inline-block;vertical-align: bottom;" href="javascript:;">删除</a>');
	                                $('#cnImgTextRead').empty().append(htmldesc);
	                                $('#cnImgTextReadBox').show();
	                            }
	                            else {
	                                showHideFn($('#cnHandleBox'), $('.cnBoxCon'));
	                            }
	                        }
	                        else {
	                            showHideFn($('#cnHandleBox'), $('.cnBoxCon'));
	                        }
	                    }
	                }
	            });
	        }
	        $('.sDl dd').removeAttr('bOn').removeClass('bgf4f5f9');
	        $('.sDl dt').removeAttr('bOn');
	        $(this).attr('bOn', true).addClass('bgf4f5f9');
	    }
	});
	//二级菜单移入移出
	$sDldd.live({
	    'mouseover': function () {
	        menuOnFn($(this).find('.inner_menu_link'));
	    },
	    'mouseout': function () {
	        outFn('.sDl dd');
	    },
	    'click': function () {
	        var itemName = $(this).closest('dd').find("strong").html();
	        $("#acTitle").html("二级菜单：" + itemName);
	        $('.sDl dt').removeAttr('bOn').removeClass('bgf4f5f9');
	        $('.sDl dd').removeAttr('bOn');
	        $(this).closest('.sDl').find('dd').eq($(this).index() - 1).attr('bOn', true).addClass('bgf4f5f9');
	        var itemid = $(this).closest('dd').attr('id');
	        var Param = $.param({
	            mid: itemid
	        });
	        $.ajax({ url: "Ajax.aspx?action=menudesc&t=" + Math.random(),
	            type: "POST",
	            data: Param,
	            dataType: "json",
	            processData: false,
	            error: function (datas) {
	                console.log("error:" + datas);
	            },
	            success: function (datas) {
	                console.log(datas);
	                if (datas == "" || datas == undefined) {
	                    showHideFn($('#cnHandleBox'), $('.cnBoxCon'));
	                }
	                else {
	                    var type = datas.type;
	                    var htmldesc = "";
	                    $('#cnURLError').html("");
	                    $('#cnEPImgTextAuto').empty();
	                    $("#cnEPEditer").val("");
	                    if (type == "text") {
	                        $('#cnTextInp').val(decodeURIComponent(datas.content));
	                        $("#cnHandleBox,#cnTipBox,#cnEditBox,#cnUrlBox,#cnImgTextReadBox,#cnTextReadBox").hide();
	                        $('#cnTextBox').show();
	                        $("#cnEPEditer").val(decodeURIComponent(datas.content));
	                    } else if (type == "view") {
	                        $('#cnUrlInp').val(decodeURIComponent(datas.content));
	                        $("#cnHandleBox,#cnTipBox,#cnEditBox,#cnImgTextReadBox,#cnTextReadBox,#cnTextBox").hide();
	                        $('#cnUrlBox').show();
	                    }
	                    else if (type == "mpnew") {
	                        var list = datas.list;
	                        if (list != null && list.length > 0) {
	                            $("#cnHandleBox,#cnTipBox,#cnEditBox,#cnUrlBox,#cnTextBox,#cnTextReadBox").hide();
	                            var htmldesc = '<div class="boe7e7eb cnEPITConL" style="display: inline-block;vertical-align: bottom;" itemid="' + datas.content + '">';
	                            for (var j = 0; j < list.length; j++) {
	                                if (j == 0) {
	                                    var sp = decodeURIComponent(list[j].simple);
	                                    htmldesc += '<h4 class="cnEPITH4">' +
                                        '<a href="#" class="c666">' + decodeURIComponent(list[j].title) + '</a>' +
                                    '</h4>' +
                                    '<p class="c666 cnEPITDate">' + list[j].date + '</p>' +
                                    '<div class="cnEPITimg db">' +
                                        '<img src="../UpFiles/res/' + list[j].logo + '" alt="图片" />' +
                                    '</div>' +
                                    '<p class="c666 cnEPITDate oh">' + (sp.length > 20 ? sp.substring(0, 20) + "......" : sp) + '</p>'
	                                }
	                                else {
	                                    htmldesc += '<div class="clear cnEPITDescImg">' +
                                            '<img src="../UpFiles/res/' + list[j].logo + '" class="cnEPITDescImgR fr" />' +
                                            '<div class="oh cnEPITDescImgL fl">' + decodeURIComponent(list[j].title) + '</div>' +
                                        '</div>';
	                                }
	                            }
	                            htmldesc += "</div>";
	                            $('#cnEPImgTextAuto').empty().append(htmldesc).append('<a class="cnEPITConR" style="display: inline-block;vertical-align: bottom;" href="javascript:;">删除</a>');
	                            $('#cnImgTextRead').empty().append(htmldesc);
	                            $('#cnImgTextReadBox').show();
	                        }
	                        else {
	                            showHideFn($('#cnHandleBox'), $('.cnBoxCon'));
	                        }
	                    }
	                    else {
	                        showHideFn($('#cnHandleBox'), $('.cnBoxCon'));
	                    }
	                }
	            }
	        });
	    }
	});
	
	//移出清除
	function outFn(str){
		$(str).each(function(i,e){
			if(!$(e).attr('bOn')){
				$(e).find('.menu_opr').hide();
			}
		});
		$('.sDl dt,.sDl dd,.inner_menu_link').each(function(i,e){
			if(!$(e).attr('bOn')){
				$(e).removeClass('bgf4f5f9');
			}
		});
	};

	//一级菜单编辑
	$oneEdit.live('click', function () {
	    var $strong = $(this).closest('dt').find('strong');
	    $tk.data({ bEditBig: true, oTarget: $strong, bBig: true, iNow: $(this).closest('.sDl').index() });
	    $('#tkInpTit').val($strong.text());
	    $(".tkH3").html("菜单名称名字不多于4个汉字:");
	    tkShowHideFn('addTk');
	});
	//二级菜单编辑
	$twoEdit.live('click', function(){
		var $strong = $(this).closest('dd').find('strong');
		$tk.data({ bEditBig: true, oTarget: $strong, iParNow: $(this).closest('.sDl').index(), iNow: $(this).closest('dd').index()-1});
		$('#tkInpTit').val($strong.text());
		$(".tkH3").html("菜单名称名字不多于7个汉字:");
		tkShowHideFn('addTk');
	});

	//一级菜单向上
	$oneUp.live('click', function () {
	    menuMoveFn($(this), true, true);
	    if ($(".moreTk").length > 0) { return; }
	    var $strong = $(this).closest('dt').find('strong');
	    var $tks = $(".addTk");
	    $tks.data({ bEditBig: true, oTarget: $strong, bBig: true, iNow: $(this).closest('.sDl').index() });
	    UpdateMenu($tks, "up");
	});

	//一级菜单向下
	$oneDown.live('click', function () {
	    menuMoveFn($(this), true);
	    if ($(".moreTk").length > 0) { return; }
	    var $strong = $(this).closest('dt').find('strong');
	    var $tks = $(".addTk");
	    $tks.data({ bEditBig: true, oTarget: $strong, bBig: true, iNow: $(this).closest('.sDl').index() });
	    UpdateMenu($tks, "down");
	});

	//二级菜单向上
	$twoUp.live('click', function(){
	    menuMoveFn($(this), false, true);
	    if ($(".moreTk").length > 0) { return; }
	    var $strong = $(this).closest('dd').find('strong');
	    var $tks = $(".addTk");
	    $tks.data({ bEditBig: true, oTarget: $strong, iParNow: $(this).closest('.sDl').index(), iNow: $(this).closest('dd').index() - 1 });
	    UpdateMenu($tks,"up");
	});

	//二级菜单向下
	$twoDown.live('click', function(){
	    menuMoveFn($(this));
	    if ($(".moreTk").length > 0) { return; }
	    var $strong = $(this).closest('dd').find('strong');
	    var $tks = $(".addTk");
	    $tks.data({ bEditBig: true, oTarget: $strong, iParNow: $(this).closest('.sDl').index(), iNow: $(this).closest('dd').index() - 1 });
	    UpdateMenu($tks, "down");
	});
	

};

/*
 * 隐藏所有，显示一个 
 * oShow 对象 显示哪个 id形式，或者类名索引
 * oHide 对象 隐藏哪些
*/
function showHideFn(oShow, oHide){
	oHide.hide();
	oShow.show();
};

/*
 * 菜单移动
 * obj 对象 移动谁
 * bOne 布尔值 true→一级，false→二级
 * bUp 布尔值 true→上，false→下
 */
function menuMoveFn(obj, bOne, bUp){
	var sClosest = bOne?'.sDl':'dd',
		_this = obj.closest(sClosest),
		$sibings = bUp?_this.prev():_this.next();
	if(!$sibings.length){
		addMoreTipFn(bUp?2:3);
	}else{
		if(bUp){
			if($sibings[0].nodeName.toLowerCase() == 'dt'){
				addMoreTipFn(2);
				return;
			}
			_this.insertBefore($sibings);
		}else{
			_this.insertAfter($sibings);
		}
	}
};

/*
 * 菜单选中状态针对移入移出时候
 * _this 对象 谁调用的就是谁
 * bOne true→一级，false→二级
 */
function menuOnFn(_this,bOne){
	
	var $menuOnBox = $('.sDl dt,.sDl dd,.inner_menu_link');
	$menuOnBox.each(function(i,e){
		if(!$(e).attr('bOn')){
			$(e).removeClass('bgf4f5f9');
		}
	})
	$('.sDl dd .menu_opr').each(function(i,e){
		if(!$(e).closest('dd').attr('bOn')){
			$(e).hide();
		}
	})
	$('.sDl dt .menu_opr').each(function(i,e){
		if(!$(e).closest('dt').attr('bOn')){
			$(e).hide();
		}
	})

	if(_this){
		_this.addClass('bgf4f5f9');
		
		if(bOne){
			_this.find('.menu_opr').show();
		}else{
			_this.next('.menu_opr').show();
		}
	}

};

/*
 * 添加超出提示
 * iNow 数字 1→一级菜单提示语，2→二级菜单提示语
 */
function addMoreTipFn(iNow){
	var aMoreTip = ['一级菜单最多只能三个','二级菜单最多只能5个','已经是顶部了','已经是底部了'];
	if($(".moreTk").length>0){return;}
	$('body').append('<div class="moreTk w100 f tac"><div class="cfff inner">'+ aMoreTip[iNow] +'</div></div>');
	setTimeout(function(){
		$(".moreTk").stop().animate({opacity:0},function(){
			$(this).remove();
		});
}, 2000);
return;
};
//字符长度
function len(str) {
    var l = 0;
    var a = str.split("");
    for (var i = 0; i < a.length; i++) {
        if (a[i].charCodeAt(0) < 299) {
            l++;
        } else {
            l += 2;
        }
    }
    return l;
}
//弹框操作
function tkHandleFn(){
	var $addClose = $('.addTk .tkClose,.addTk .tkBtnR'),
		$addSub = $('.addTk .tkBtnL'),
		$delClose = $('.delTk .tkClose,.delTk .tkBtnR'),
		$delSub = $('.delTk .tkBtnL'),
		$tkInpTit = $('#tkInpTit'),
		$imgSub = $('#imgSub'),
		$cnEPImgDel = $(".cnEPImgCon .cnEPImgConR"),
		$addImgClose = $('.addImgTk .tkClose,.addImgTk .tkBtnR'),
		$addImgSub = $('.addImgTk .tkBtnL'),
		$addImgTextClose = $('.addImgTextTk .tkClose,.addImgTextTk .tkBtnR'),
		$addImgTextSub = $('.addImgTextTk .tkBtnL'),
		$cnEPImgTextDel = $(".cnEPITCon .cnEPITConR"),
		$imgList = $('#imgList li'),
		$imgTextList = $('.imgTextList li');
	    $tk = $('.addTk'),
		$delTk = $('.delTk'),
		$tkError= $('.tkError'),
		re = /^([a-zA-Z]|[\u4E00-\u9FA5])*$/,
		reC = /[\u4E00-\u9FA5]/g,
		aTip = ['输入框内容不能为空', '输入框内容只能是字母或者汉字', '菜单名称名字不多于4个汉字', '菜单名称名字不多于7个汉字'];

	    $addClose.click(function () {
	        tkShowHideFn('addTk', true);
	        resetInfoTkFn();
	    });
	    //添加弹框
	    $addSub.click(function () {
	        var iTkInpTit = $tkInpTit.val(),
			iNewLength = iTkInpTit.replace(reC, "aa").length;

	        $tkError.text('');
	        if (!iTkInpTit) {
	            $tkError.text(aTip[0]);
	            return;
	        }
//	        if (!re.test(iTkInpTit)) {
//	            $tkError.text(aTip[1]);
//	            return;
//	        }	        

	        if ($tk.data('bEditBig')) {//编辑
	            if ($tk.data("bBig")) { //一级
	                if (len(iTkInpTit) > 8) {
	                    $tkError.text(aTip[2]);
	                    return;
	                }
	                //alert($('.sDl').length);
	                //	            alert($tk.data('iNow'));
	                //	            alert($('.sDl').eq($tk.data('iNow')).find('dt').attr('id'));
	            } else { //二级
	                if (len(iTkInpTit) > 14) {
	                    $tkError.text(aTip[3]);
	                    return;
	                }
	                //	            alert($tk.data('iNow'));
	                //	            alert($('.sDl').eq($tk.data('iParNow')).find('dd').eq($tk.data('iNow')).attr('id'));
	            }
	            editDataFn();
	        } else {    //添加
	            if ($tk.data("bBig")) { //一级
	                if (len(iTkInpTit) > 8) {
	                    $tkError.text(aTip[2]);
	                    return;
	                }
	                //	            alert($('.sDl').length);
	            } else { //二级
	                if (len(iTkInpTit) > 14) {
	                    $tkError.text(aTip[3]);
	                    return;
	                }
	                //	            alert($tk.data('iNow'));
	                //	            alert($('.sDl').eq($tk.data('iNow')).find('dd').attr('id'));
	            }
	            addDataFn();
	        }

	        tkShowHideFn('addTk', true);

	    });
	$delClose.click(function () {
	    tkShowHideFn('delTk', true);
	    resetInfoTkFn();
	});
	//删除弹框
	$delSub.click(function () {
	    var itemid = "0";
	    if ($delTk.attr("bBig")) { //一级
	        itemid = $('.sDl').eq($delTk.attr('iNow')).find('dt').attr('id');
	    } else { //二级
	        itemid = $('.sDl').eq($delTk.attr('iNow')).find('dd').eq($delTk.attr('iDDNow')).attr('id');
	    }
	    var Param = $.param({
	        mid: itemid,
	        action: "delmenu"
	    });
	    $.ajax({ url: "Ajax.aspx?t=" + Math.random(),
	        type: "POST",
	        data: Param,
	        processData: false,
	        error: function (datas) {
	            ispost = false;
	            alert("网络繁忙请稍后再试！");
	        },
	        success: function (datas) {
	            if (datas == "ok") {
	                tkShowHideFn('delTk', true);
	                deleteDataFn();
	            }
	            else {
	                alert("网络繁忙请稍后再试！");
	            }
	        }
	    });

	});

	$addImgClose.click(function () {
	    tkShowHideFn('addImgTk', true);
	    resetInfoTkFn();
	    reSetImgFn();
	});
	
	//选择图片添加
	$imgSub.click(function(){
		var $clone = $('#imgList li[bClick=true]');
		//$('#imgList li[bClick=true]').clone().appendTo('#cnEPImg');
		
//		var sCnEPHtml = '<div class="clear cnEPImgCon">'+
//							'<div class="cnEPImgConL fl">'+
//								'<a href="'+$clone.find('img').attr('src')+'" class="db">'+
//									'<img src="'+ $clone.find('img').attr('src') +'" alt="图片" />'+
//								'</a>'+
//							'</div>'+
//							'<a class="cnEPImgConR fl" href="javascript:;">删除</a>'+
//						'</div>';
		var sCnEPHtml = '<div class="clear cnEPImgCon">' +
							'<div class="cnEPImgConL fl">' +
								'<img width="300px" src="../UpFiles/res/' + $("#selPic").val() + '" alt="图片" />' +
							'</div>' +
						'</div>';
		$('#cnEPImg').html(sCnEPHtml);

		tkShowHideFn('addImgTk',true);
		reSetImgFn();
	});

	//选择图片移入移出
	$imgList.live({
		'click': function(){
			reSetImgFn();
			$(this).closest('li').attr('bClick', true);
			$(this).find('.selected_mask .selected_mask_icon').show();
		},
		'mouseover': function(){
			$(this).find('.selected_mask').show();
		},
		'mouseout': function(){
		    $('#imgList li').each(function (i, e) {
				if(!$(e).attr('bClick')){
					$(e).find('.selected_mask').hide();
				}
			});
		}
	});

	//选择图片删除
	$cnEPImgDel.live('click', function(){
		$(this).closest('.cnEPImgCon').remove();
	});

	$addImgTextClose.click(function () {

	    //if ($("#divDisable").length>0) {
	    //    CloseOpenedDiv();
	    //}
	    tkShowHideFn('addImgTextTk', true);
	    resetInfoTkFn();
	    reSetImgTextFn();
	});
	
	//选择图文添加
	$addImgTextSub.click(function () {

	    var $clone = $('.imgTextList li[bClick=true]').find('.cnEPITConL').css({ 'display': 'inline-block', 'vertical-align': 'bottom' });
	    //var $cloneUp = $cnTab.eq(2).find('.getCon').html();
	    //$('#cnEPImgTextAuto').empty().append($clone.clone()).append('<a class="cnEPITConR" style="display: inline-block;vertical-align: bottom;" href="javascript:;">删除</a>');
	    $('#cnEPImgTextAuto').empty().append($clone.clone());

	    $('#KContentTB').val($('#cnEPImgTextAuto .cnEPITConL').attr("itemid"));

	    tkShowHideFn('addImgTextTk', true);
	    reSetImgTextFn();
	});
	//选择图文删除
	$cnEPImgTextDel.live('click', function () {
	    $(this).closest('.cnEPITCon').empty();
	});
	$('.cnEPImgTextAuto .cnEPITConR').live('click', function () {
	    $(this).closest('#cnEPImgTextAuto').empty();
	}); 

	//图文移入移出
	$imgTextList.live({
	    'click': function () {
	        reSetImgTextFn();
	        $('.imgTextList li').removeAttr('bClick');
	        $(this).closest('li').attr('bClick', true);
	        $(this).find('.cnEPITMask .icon_card_selected').show();
	    },
	    'mouseover': function () {
	        $(this).find('.cnEPITMask').show();
	    },
	    'mouseout': function () {
	        $('.imgTextList li').each(function (i, e) {
	            if (!$(e).attr('bClick')) {
	                $(e).find('.cnEPITMask').hide();
	            }
	        });
	    }
	});
	
	//选择图文重置
	function reSetImgTextFn(){
		$imgTextList.removeAttr('bClick');
		$('.cnEPITMask,.icon_card_selected').hide();
	};
	//选择图片重置
	function reSetImgFn(){
		$imgList.removeAttr('bClick');
		$('.selected_mask,.selected_mask_icon').hide();
	};	
};

//添加菜单数据
var ispost = false;
function addDataFn() {
	var stkInpTit = $('#tkInpTit').val(),
		sMenuBigHtml = 
							'<strong>'+ stkInpTit +'</strong>'+
							'<span class="a menu_opr dn">'+
								'<a href="javascript:void(0);" class="cw icon14_common add_gray">添加</a>'+
								'<a href="javascript:void(0);" class="cw icon14_common  edit_gray">编辑</a>'+
								'<a href="javascript:void(0);" class="cw icon14_common up_gray">↑</a>'+
								'<a href="javascript:void(0);" class="cw icon14_common down_gray">↓</a>'+
								'<a href="javascript:void(0);" class="cw icon14_common del_gray">删除</a>'+
							'</span>',
		sMenuSmallHtml = 
					'<i class="a cd5d5d5 icon_dot">●</i>'+
					'<a href="javascript:void(0);" class="inner_menu_link"><strong>'+ stkInpTit +'</strong></a>'+
					'<span class="a menu_opr dn">'+
						'<a href="javascript:void(0);" class="icon14_common edit_gray">编辑</a>'+
						'<a href="javascript:void(0);" class="icon14_common del_gray">删除</a>'+
						'<a href="javascript:void(0);" class="cw icon14_common up_gray">↑</a>'+
						'<a href="javascript:void(0);" class="cw icon14_common down_gray">↓</a>'+
					'</span>',
		$sArea = $('#sArea'),
		$tk = $('.addTk');
	
	$('.sDl dt,.sDl dd').removeAttr('bOn');

	if ($tk.data('bBig')) {//一级菜单添加
	    var name = stkInpTit;
	    var sort = ($('.sDl').length+1);
	    var pid = '';
	    var level = 1;
	    var Param = $.param({
	        name: name,
	        sort: sort,
	        pid: pid,
	        level: level,
	        action: "addmenu"
	    });
	    if (!ispost) {
	        ispost = true;
	        $.ajax({ url: "Ajax.aspx?t=" + Math.random(),
	            type: "POST",
	            data: Param,
	            processData: false,
	            error: function (datas) {
	                ispost = false;
	                alert("网络繁忙请稍后再试！");
	            },
	            success: function (datas) {
	                ispost = false;
	                var splist = datas.split('_');
	                if (splist.length == 2) {
	                    var $addDl = $('<dl>'),
			            $addDt = $('<dt>').attr({ id: splist[1], sort: sort, level: 1 });
	                    $sArea.append($addDl);
	                    $addDl.addClass('bobe7e7eb sDl');
	                    $addDt.addClass('r fs14').attr('bOn', true);
	                    $addDl.append($addDt);
	                    $addDt.append(sMenuBigHtml);
	                    menuOnFn($addDl.find('dt'), true);
	                }
	                else if (splist.length == 1 && splist[0] != "fail") {
	                    alert(splist[0]);
	                }
	                else {
	                    alert("网络繁忙请稍后再试！");
	                }
	            }
	        });
	    }

	} else {
	    var name = stkInpTit,
            $DD = $('.sDl').eq($('.addTk').data('iNow')).find('dt');
	    var sort = ($('.sDl').eq($('.addTk').data('iNow')).find('dd').length + 1);
	    var pid = $DD.attr('id');
	    var level = 2;
	    var Param = $.param({
	        name: name,
	        sort: sort,
	        pid: pid,
	        level: level,
	        action: "addmenu"
	    });
	    if (!ispost) {
	        ispost = true;
	        $.ajax({ url: "Ajax.aspx?t=" + Math.random(),
	            type: "POST",
	            data: Param,
	            processData: false,
	            error: function (datas) {
	                ispost = false;
	                alert("网络繁忙请稍后再试！");
	            },
	            success: function (datas) {
	                ispost = false;
	                var splist = datas.split('_');
	                if (splist.length == 2) {
	                    var $addDD = $('<dd>').attr({id:splist[1],sort: sort, pid: pid, level: 2 }),
			            $addDl = $('.sDl').eq($tk.data('iNow'));
	                    $addDD.addClass('r lh32').attr('bOn', true);
	                    $addDD.append(sMenuSmallHtml);
	                    $addDl.append($addDD);
	                    menuOnFn($addDl.find('dd').eq(-1), true);
	                }
	                else {
	                    alert("网络繁忙请稍后再试！");
	                }
	            }
	        });
	    }	
	}
	resetInfoTkFn();
};

//显示字数
function showWordsCount() {
    var sEdit = $("#cnEPEditer").val().replace(/[\r\n]/g, ""),
			iEditLen = 0;
    if (600 - sEdit.length >= 0) {
        $('#cnEPEditTipText').text('还可以输入' + (600 - sEdit.length) + '字');
    } else {
        iEditLen = sEdit.length;
        $('#cnEPEditTipText').text('已经超出' + (sEdit.length - 600) + '字');
    }
}

//清空弹框内容
function resetInfoTkFn(){
	$('.tkError').text('');
	$('#tkInpTit').val('');
	$('.addTk').removeData('bBig bEditBig');
	$('.delTk').removeAttr('bBig iDDnow iNow');
};

/*
 *删除菜单数据
 * btn 布尔值 true→一级菜单删除 false→二级菜单删除
*/
function deleteDataFn(){
	var $delTk = $('.delTk'),
		$sDl = $('.sDl'),
		iNow = $delTk.attr('iNow'),//删除第几个dl
		bBig = $delTk.attr('bBig');//true→一级菜单，false→二级菜单

	if(bBig){
		$sDl.eq(iNow).remove();
} else {
    var iDDNow = $delTk.attr('iDDNow'); //删除第几个dd
		$sDl.eq(iNow).find('dd').eq(iDDNow).remove();
	}

};

//编辑菜单数据
function editDataFn() {
    var $sArea = $('#sArea'),
		$tk = $('.addTk'), $mName, $mid, $sort;

    if ($tk.data('bEditBig')) {
        var $oTarget = $tk.data('oTarget');
        $oTarget.text($('#tkInpTit').val());
        $mName = $('#tkInpTit').val();
    } else {
        var $addDl = $('.sDl').eq($tk.data('iNow'));
        $addDl.append(sMenuSmallHtml);
        menuOnFn($addDl.find('dd').eq(-1), true);
    }
    UpdateMenu($tk);
    resetInfoTkFn();
}

//右边操作
function conHandleFn(){
	var $cnToHome = $('#cnToHome'),
		$cnPushInfo = $('#cnPushInfo'),
		$cnEditBack = $('#cnEditBack'),
		$resetAction = $('.resetAction'),
		$cnUrlSub = $('#cnUrlSub'),
		$cnENbtn = $('.cnENbtn'),
		$cnEPEditTipText = $('#cnEPEditTipText'),
		$cnEPItemBox = $('#cnEPItemBox'),
		$cnEPEditer = $('#cnEPEditer'),
		$cnTab = $('.cnTab'),
		$cnEditSub =$('#cnEditSub'),
		$cnReadBox = $('.cnReadBox'),
		$cnBoxCon = $('.cnBoxCon');

	$cnToHome.click(function () {
	    showHideFn($('#cnUrlBox'), $('.cnBoxCon'));
	    $('#cnUrlInp').val('');
	});

	$cnPushInfo.click(function () {
	    $('.cnTab').hide().eq(0).show();
	    showHideFn($('#cnEditBox'), $('.cnBoxCon'));
	    $('#cnEPEditer').val('');
	    $('#cnEPITCon,#cnEPImgTextAuto').empty();
	    $('.cnENbtn').removeClass('cnENbtnOn').eq(0).addClass('cnENbtnOn');
	});

	$cnEditBack.click(function () {
	    var iReadIndex = 0;
	    $cnENbtn.each(function (i,e) {
	        if ($(e).hasClass('cnENbtnOn')) {
	            iReadIndex = $(e).index();
	        }
	    });
	    if (iReadIndex == 0) {
	        $('#cnTextBox').show();
	        $("#cnHandleBox,#cnTipBox,#cnEditBox,#cnUrlBox,#cnImgTextReadBox,#cnTextReadBox").hide();
	    }
	    else if (iReadIndex == 1) {
	        $('#cnImgReadBox').show();
	        $("#cnHandleBox,#cnTipBox,#cnEditBox,#cnUrlBox,#cnImgTextReadBox,#cnTextReadBox").hide();
	    }
	    else if (iReadIndex == 2) {
	        $('#cnImgTextReadBox').show();
	        $("#cnHandleBox,#cnTipBox,#cnEditBox,#cnUrlBox,#cnTextBox,#cnTextReadBox").hide();
	    }
	});
	$resetAction.click(function () {
	    ReSetMenu();
	    showHideFn($('#cnHandleBox'), $('.cnBoxCon'));
	    $('#cnEPEditer,#cnEPImg,#cnEPITCon').empty();
	    $('.cnENbtn').removeClass('cnENbtnOn').eq(0).addClass('cnENbtnOn');
	    $('cnTab').hide().eq(0).show();
	});
	
	//URL确定事件
	$cnUrlSub.click(function () {
	    var re = new RegExp("^((https|http|ftp|rtsp|mms)://)?[a-z0-9A-Z]{3}\.[a-z0-9A-Z][a-z0-9A-Z]{0,61}?[a-z0-9A-Z]\.com|net|cn|cc (:s[0-9]{1-4})?/$");
	    var urlct = $('#cnUrlInp').val();
//	    if (re.test(urlct)) {
//	        var menuid = $('.sDl dd[bon="true"],.sDl dt[bon="true"]').attr("id");
//	        UpdateData(menuid, urlct, "view");
//	        $('#cnURLError').html("编辑URL成功");
//	    } else {
//	        $('#cnURLError').html('请输入正确的URL');
//	    }
	    var menuid = $('.sDl dd[bon="true"],.sDl dt[bon="true"]').attr("id");
	    UpdateData(menuid, urlct, "view");
	    $('#cnURLError').html("编辑URL成功");
	});
	
	//编辑选择事件
	$cnENbtn.click(function () {
	    var iNow = $(this).index(),
			$addImgTk = $('#addImgTk'),
			$addImgTextTk = $('#addImgTextTk');
	    reSetEdit();
	    $cnENbtn.removeClass('cnENbtnOn').eq(iNow).addClass('cnENbtnOn');
	    $cnTab.hide().eq(iNow).show();
	    $("#ShowTypeTB").val(iNow);
	    switch (iNow) {
	        case 1:
	            tkShowHideFn('addImgTk');
	            break;
	        case 2:
	            tkShowHideFn('addImgTextTk');
	            break;
	    }

	});

	//编辑限制字数
	$cnEPEditer.keydown(function () {
	    var sEdit = $(this).val().replace(/[\r\n]/g, ""),
			iEditLen = 0;
	    if (600 - sEdit.length >= 0) {
	        $cnEPEditTipText.text('还可以输入' + (600 - sEdit.length) + '字');
	    } else {
	        iEditLen = sEdit.length;
	        $cnEPEditTipText.text('已经超出' + (sEdit.length - 600) + '字');
	    }
	});

	//编辑提交
	$cnEditSub.click(function () {
	    $cnENbtn.each(function (i, e) {
	        if ($(e).hasClass('cnENbtnOn')) {
	            var iReadIndex = $(e).index(),
					sHTML = $cnTab.eq(iReadIndex).children().html();
	            if (iReadIndex == 0) {
	                sHTML = $("#cnEPEditer").val();
	            }
	            if (sHTML == "" || sHTML == undefined) {
	                alert("内容不能为空");
	            }
	            else {
	                $cnBoxCon.hide();
	                $cnReadBox.hide();
	                switch (iReadIndex) {
	                    case 0:
	                        $('#cnTextBox').show();
	                        textReadFn($("#cnEPEditer").val());
	                        break;
	                    case 1:
	                        if (sHTML.indexOf("itemid") > -1) {
	                            $('#cnImgReadBox').show();
	                            imgReadFn(sHTML);
	                        }
	                        break;
	                    case 2:
	                        if (sHTML.indexOf("itemid") > -1) {
	                            $('#cnImgTextReadBox').show();
	                            imgTextReadFn(sHTML);
	                        }
	                        break;
	                }
	            }
	        }
	    });
	});
	
	//文字修改按钮
	$('#cnTextRevise').click(function () {
	    $("#cnHandleBox,#cnTipBox,#cnUrlBox,#cnImgTextReadBox,#cnTextReadBox,#cnTextBox").hide();
	    $('#cnEditBox').show();
	    $('.cnTab').hide().eq(0).show();
	    $('.cnENbtn').removeClass('cnENbtnOn').eq(0).addClass('cnENbtnOn');
	    $cnReadBox.hide();
	});
	$('.reviseBtn').click(function () {
	    $("#cnHandleBox,#cnTipBox,#cnUrlBox,#cnImgTextReadBox,#cnTextReadBox").hide();
	    $('#cnEditBox').show();
	    $('.cnTab').hide().eq(2).show(); 
	    var $clone = $('#cnImgTextRead').find(".cnEPITConL").css({ 'display': 'inline-block', 'vertical-align': 'bottom' });
	    $('#cnEPITCon').empty().append($('#cnImgTextRead').html()).append('<a class="cnEPITConR" style="display: inline-block;vertical-align: bottom;" href="javascript:;">删除</a>');
	    $('.cnENbtn').removeClass('cnENbtnOn').eq(2).addClass('cnENbtnOn');
	    $cnReadBox.hide();
	});

	//文字
	function textReadFn(sHTML) {
		var $cnTextReadInp = $('#cnTextInp');
		$cnTextReadInp.val(sHTML);
		var menuid = $('.sDl dd[bon="true"],.sDl dt[bon="true"]').attr("id");
		var level = $('.sDl dd[bon="true"],.sDl dt[bon="true"]').attr("level");
		UpdateData(menuid, sHTML, "text");
	};

	//图片
	function imgReadFn(sHTML) {
	    $('#cnImgRead').empty().append(sHTML);
	};

	//图文
	function imgTextReadFn(sHTML) {
	    sHTML=sHTML.replace('<a class="cnEPITConR" style="display: inline-block;vertical-align: bottom;" href="javascript:;">删除</a>', "");
	    $('#cnImgTextRead').empty().append(sHTML);
	    var itemid = $('#cnImgTextRead .cnEPITConL').attr("itemid");
	    var menuid = $('.sDl dd[bon="true"],.sDl dt[bon="true"]').attr("id");
	    UpdateData(menuid, itemid, "mpnew");
	};

};

//编辑框中重置数据
function reSetEdit(){
	$('#cnEPImg,#cnEPITCon').html('');
};
var isup = false;
function UpdateData(mid, sid, type) {
    var Param = $.param({
        mid: mid,
        sid: sid,
        type:type
    });
    if (!isup) {
        isup = true;
        $.ajax({ url: "Ajax.aspx?action=resetmenu&t=" + Math.random(),
            type: "POST",
            data: Param,
            processData: false,
            error: function (datas) {
                isup = false;
            },
            success: function (datas) {
                isup = false;
            }
        });
    }
}
function UpdateMenu($tk,ctr) {
    var $mName, $mid, $sort;
    if ($tk.data("bBig")) { //一级
        $mid = $('.sDl').eq($tk.data('iNow')).find('dt').attr('id');
        if (ctr != '' && ctr != undefined) {
            $mName = $('.sDl').eq($tk.data('iNow')).find('dt').find('strong').html();
        }
        else {
            $mName = $tk.data("oTarget").text();
        }
        $sort = $('.sDl').eq($tk.data('iNow')).find('dt').attr('sort');
    } else { //二级
        $mid = $('.sDl').eq($tk.data('iParNow')).find('dd').eq($tk.data('iNow')).attr('id');
        if (ctr != '' && ctr != undefined) {
            $mName = $('.sDl').eq($tk.data('iParNow')).find('dd').find('strong').html();
        }
        else {
            $mName = $tk.data("oTarget").text();
        }
        
        $sort = $('.sDl').eq($tk.data('iParNow')).find('dd').eq($tk.data('iNow')).attr('sort');
    }
    var Param = $.param({
        mid: $mid,
        name: $mName,
        sort: $sort,
        ctr: ctr
    });
    $.ajax({ url: "Ajax.aspx?action=upmenu&t=" + Math.random(),
        type: "POST",
        data: Param,
        processData: false,
        error: function (datas) {
        },
        success: function (datas) {
            window.location.href = "WXMenuList.aspx";
        }
    });
}
function ReSetMenu() {
    var menuid = $('.sDl dd[bon="true"],.sDl dt[bon="true"]').attr("id");
    var Param = $.param({
        mid: menuid
    });
    $.ajax({ url: "Ajax.aspx?action=clearmenu&t=" + Math.random(),
        type: "POST",
        data: Param,
        processData: false,
        error: function (datas) {
        },
        success: function (datas) {
        }
    });
}